package cn.sh.yhk.acl.service;

import cn.sh.yhk.acl.AuthentUser;
import cn.sh.yhk.acl.UserDetailsInfo;
import cn.sh.yhk.acl.cache.UserTokenCacheService;
import cn.sh.yhk.acl.jwt.JwtTokenUtil;
import cn.sh.yhk.base.vo.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname Yhk
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/10/3 15:08
 * @Created by y6522
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {


    @Autowired
    private UserTokenCacheService userTokenCacheService;
    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public Map<String, String> login(AuthentUser authentUser) {
        Map<String, String> loginMap = new HashMap<>();

        //封装 Authentication
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authentUser.getUsername(),
                authentUser.getPassword());
        //认证用户
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate == null) {
            throw new RuntimeException("认证失败！");
        }
        String token = "";
        //获取认证用户信息
        UserDetailsInfo userDetailsInfo = (UserDetailsInfo) authenticate.getPrincipal();
        //认证通过，生成jwt
        token = JwtTokenUtil.generateToken(userDetailsInfo);
        //存入缓存中
        userTokenCacheService.userTokenCachePut(token);
        loginMap.put("username", userDetailsInfo.getUsername());
        loginMap.put("token", token);
        return loginMap;

    }
}
